package JDBC_1.preparedstatement;

import JDBC_1.StatementTest.User;
import JDBC_1.util.JDBCUtils;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Scanner;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/5/13 11:15
 * @description： 解决SQL注入问题
 *
 *除了解决Statement的拼串、sq1问题之外，Preparedstatement还有哪些好处呢?
 * 1. Preparedstatement操作Blob的数据，而Statement做不到。
 * 2. PreparedStatement可以实现更高效的批量操作。
 */
public class PreparedStatementTest {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.print("用户名：");
        String user = scan.nextLine();//Line就是只以换行来作为数据的结束
        System.out.print("密   码：");
        String password = scan.nextLine();

        // SELECT user,password FROM user_table WHERE USER = '1' or ' AND PASSWORD = '
        // ='1' or '1' = '1';
        String sql = "SELECT user,password FROM user_table WHERE user = ? and password = ?";
        User returnsuer = getInstance(User.class, sql, user, password);
        if (returnsuer != null) {
            System.out.println("登陆成功!");
        } else {
            System.out.println("用户名或密码错误！");
        }
    }

    public static <T> T getInstance(Class<T> clazz, String sql, Object... args) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            //执行，获得结果集
            rs = ps.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            //获取字段据个数
            int columnCount = rsmd.getColumnCount();
            if (rs.next()) {
                //获取一个类的对象
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取每一个列的列值:通过resultset
                    Object columnValue = rs.getObject(i + 1);
                    //获取列的别名：getcolumnlabel（）推荐使用
                    String columnName = rsmd.getColumnLabel(i + 1);
                    //通过反射将对象指定属性名的属性赋值
                    Field field = clazz.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResourece(connection, ps, rs);
        }
        return null;
    }
}
